package lpath

import (
	"cmp"
	"slices"
	"strings"

	"github.com/shirou/gopsutil/v3/disk"
)

// MonutPoint 获取磁盘挂载点, 并从长到短排序
func MonutPoints() []string {
	dps, _ := disk.Partitions(false)
	ps := make([]string, 0, len(dps))
	for _, partition := range dps {
		ps = append(ps, partition.Mountpoint)
	}
	// 从长到短排序
	slices.SortStableFunc(ps, func(i, j string) int {
		return -cmp.Compare(len(i), len(j))
	})
	return ps
}

// MatchMountPoint 目录路径最长匹配到挂载点
func MatchMountPoint(path string, mps []string) string {
	if !strings.HasSuffix(path, "/") {
		path = path + "/"
	}

	for _, mp := range mps {
		if !strings.HasSuffix(mp, "/") {
			mp = mp + "/"
		}
		if strings.HasPrefix(path, mp) {
			if mp == "/" {
				return mp
			}
			return mp[:len(mp)-1]
		}
	}
	return ""
}
